import Promise from 'promise';
import * as SubmenuProxy from './submenu';
import * as ResultMsg from '../constrants/ResultMsg';
import { MenuModel } from '../models';

const fields = null;

export async function find(appId, conditions, options) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof conditions !== 'object') throw new Error(ResultMsg.NOT_OBJECT);
  if (typeof options !== 'object') options = null;
  conditions.appId = appId;

  try {
    const menus = await MenuModel.find(conditions).setOptions(options).exec();
    if (menus.length < 1) {
      return Promise.resolve(menus);
    }

    const newMenus = [];
    for (let i = 0, len = menus.length; i < len; i++) {
      newMenus[i] = menus[i].toObject();
    }

    const submenus = await SubmenuProxy.find(appId, { deleted: false });

    for (let i = 0; i < newMenus.length; i++) {
      const sub = [];
      for (let j = 0; j < submenus.length; j++) {
        if (newMenus[i]._id.toString() === submenus[j].parent_id.toString()) {
          sub.push(submenus[j].toObject());
        }
      }

      newMenus[i].submenus = sub;
    }

    return Promise.resolve(newMenus);
  } catch (err) {
    logger.error(err);
    return Promise.reject(err);
  }
}

export function findOne(appId, conditions, options) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof conditions !== 'object') throw new Error(ResultMsg.NOT_OBJECT);
  if (typeof options !== 'object') options = null;
  conditions.appId = appId;
  const query = MenuModel.findOne(conditions).select(fields).setOptions(options);
  return query.exec();
}

export function findOneById(appId, id) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof id !== 'string' && typeof id !== 'object') throw new Error(ResultMsg.NO_ID);
  const query = MenuModel.findOne({appId: appId, _id: id }).select(fields);
  return query.exec();
}

export function update(appId, id, data) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof id !== 'string' && typeof id !== 'object') throw new Error(ResultMsg.NO_ID);
  if (typeof data !== 'object') throw new Error(ResultMsg.NOT_OBJECT);
  const query = MenuModel.findByIdAndUpdate(id, { $set: data });
  return query.exec();
}

export function create(appId, zoneId, key, value) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof zoneId !== 'string' && typeof zoneId !== 'object') throw new Error(ResultMsg.NO_ID);
  if (typeof key !== 'string') throw new Error(ResultMsg.NOT_STRING);
  if (typeof value !== 'string') throw new Error(ResultMsg.NOT_STRING);
  const doc = new MenuModel();
  doc.appId = appId;
  doc.zoneId = zoneId;
  doc.key = key;
  doc.value = value;
  return doc.save();
}
